package com.tengfei.main.exam.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tengfei.common.constant.UserConstants;
import com.tengfei.common.core.domain.PageQuery;
import com.tengfei.common.core.page.TableDataInfo;
import com.tengfei.common.exception.ServiceException;
import com.tengfei.common.helper.DataBaseHelper;
import com.tengfei.common.utils.StringUtils;
import com.tengfei.main.exam.domain.Paper;
import com.tengfei.main.exam.domain.PaperQu;
import com.tengfei.main.exam.domain.PaperUser;
import com.tengfei.main.exam.domain.bo.PaperBo;
import com.tengfei.main.exam.domain.bo.PaperQuQueryBo;
import com.tengfei.main.exam.domain.bo.PaperUserBo;
import com.tengfei.main.exam.domain.bo.PaperQuBo;
import com.tengfei.main.exam.domain.vo.PaperObjQuVo;
import com.tengfei.main.exam.domain.vo.PaperUserVo;
import com.tengfei.main.exam.domain.vo.PaperVo;
import com.tengfei.main.exam.mapper.PaperMapper;
import com.tengfei.main.exam.mapper.PaperUserMapper;
import com.tengfei.main.exam.mapper.PaperQuMapper;
import com.tengfei.main.exam.service.IPaperService;
import com.tengfei.main.question.domain.vo.ObjectiveVo;
import com.tengfei.main.question.domain.vo.SubjectiveVo;
import com.tengfei.main.system.domain.SysDept;
import com.tengfei.main.system.domain.SysUser;
import com.tengfei.main.system.mapper.SysDeptMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 试卷Service业务层处理
 *
 * @author tengfei
 * @date 2022-07-31
 */
@Service
public class PaperServiceImpl implements IPaperService {

    @Resource
    private PaperMapper baseMapper;
    @Resource
    private PaperQuMapper questionMapper;
    @Resource
    private SysDeptMapper deptMapper;
    @Resource
    private PaperUserMapper paperUserMapper;

    /**
     * 查询试卷
     */
    @Override
    public PaperVo queryById(Long PaperId) {
        return baseMapper.selectVoById(PaperId);
    }

    /**
     * 查询试卷列表
     */
    @Override
    public TableDataInfo<PaperVo> queryPageList(PaperBo bo, PageQuery pageQuery) {
        Page<PaperVo> result = baseMapper.selectVoPage(pageQuery.build(), new LambdaQueryWrapper<Paper>()
                .eq(ObjectUtil.isNotNull(bo.getPaperName()), Paper::getPaperName, bo.getPaperName())
                .eq(ObjectUtil.isNotNull(bo.getPaperName()), Paper::getPaperDesc, bo.getPaperName())
                .eq(ObjectUtil.isNotNull(bo.getPaperStatus()), Paper::getPaperStatus, bo.getPaperStatus())
                .orderByDesc(Paper::getUpdateTime));
        return TableDataInfo.build(result);
    }


    /**
     * 新增试卷
     */
    @Override
    public Boolean insertByBo(PaperBo bo) {
        // 合格分数
        if (bo.getPaperPassScore().intValue() < 0) {
            throw new ServiceException("请输入正常的合格分数");
        }
        // 合格时间段
        if (bo.getPaperStartTime().getTime() >= bo.getPaperEndTime().getTime()) {
            throw new ServiceException("请输入正常的考试时间段");
        }
        Paper paper = BeanUtil.toBean(bo, Paper.class);
        return baseMapper.insert(paper) > 0;
    }

    /**
     * 修改试卷
     */
    @Override
    public Boolean updateByBo(PaperBo bo) {
        // 合格分数
        if (bo.getPaperPassScore().intValue() < 0) {
            throw new ServiceException("请输入正常的合格分数");
        }
        // 合格时间段
        if (bo.getPaperStartTime().getTime() >= bo.getPaperEndTime().getTime()) {
            throw new ServiceException("请输入正常的考试时间段");
        }
        Paper update = BeanUtil.toBean(bo, Paper.class);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 批量删除试卷
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 查询试卷已绑定题目列表
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo bindQuList(PaperQuQueryBo bo, PageQuery pageQuery) {
        if (ObjectUtil.isNull(bo.getQuType())) {
            throw new ServiceException("题目类型为空");
        }
        if (ObjectUtil.isNull(bo.getPaperId())) {
            throw new ServiceException("试卷id为空");
        }
        if (isObj(bo.getQuType())) {
            Page<PaperObjQuVo> bindObjQuList = questionMapper.getBindObjQuList(pageQuery.build(), bo);
            return TableDataInfo.build(bindObjQuList);
        } else {
            Page<PaperObjQuVo> bindSubQuList = questionMapper.getBindSubQuList(pageQuery.build(), bo);
            return TableDataInfo.build(bindSubQuList);
        }

    }

    /**
     * 查询试卷未绑定题目列表
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo unBindQuList(PaperQuQueryBo bo, PageQuery pageQuery) {
        if (ObjectUtil.isNull(bo.getQuType())) {
            throw new ServiceException("题目类型为空");
        }
        if (ObjectUtil.isNull(bo.getPaperId())) {
            throw new ServiceException("试卷id为空");
        }
        if (isObj(bo.getQuType())) {
            Page<ObjectiveVo> unBindObjQuList = questionMapper.getUnBindObjQuList(pageQuery.build(), bo);
            return TableDataInfo.build(unBindObjQuList);
        } else {
            Page<SubjectiveVo> unBindSubQuList = questionMapper.getUnBindSubQuList(pageQuery.build(), bo);
            return TableDataInfo.build(unBindSubQuList);
        }
    }

    /**
     * 修改题目分数
     *
     * @param bo
     * @return
     */
    @Transactional
    @Override
    public boolean updateQuScore(PaperQuBo bo) {
        if (ObjectUtil.isNull(bo.getId()) || ObjectUtil.isNull(bo.getQuScore())
                || ObjectUtil.isNull(bo.getPaperId())) {
            throw new ServiceException("id/试卷id/题目分数未空");
        }
        // 获取试卷原分数
        Integer quScore = questionMapper.selectById(bo.getId()).getQuScore();
        int score = bo.getQuScore() - quScore;
        // 修改试卷总分
        int res1 = baseMapper.update(null, new LambdaUpdateWrapper<Paper>()
                .setSql(" `paper_now_score`=`paper_now_score`+" + score)
                .eq(Paper::getPaperId, bo.getPaperId()));
        // 修改题目分数
        int res2 = questionMapper.update(null, new LambdaUpdateWrapper<PaperQu>()
                .set(PaperQu::getQuScore, bo.getQuScore())
                .eq(PaperQu::getId, bo.getId()));

        return res1 > 0 && res2 > 0;
    }

    /**
     * 试卷批量绑定题目
     *
     * @param bos
     * @return
     */
    @Transactional
    @Override
    public boolean addQuByQuBo(List<PaperQuBo> bos) {
        if (bos.size() <= 0) {
            throw new ServiceException("待添加列表小于1");
        }
        Integer increaseScore = bos.stream().map(bo -> bo.getQuScore())
                .reduce(0, (totalScore, score) -> totalScore + score);
        // 绑定题目
        List<PaperQu> questions = BeanUtil.copyToList(bos, PaperQu.class);
        boolean res1 = questionMapper.insertBatch(questions);
        // 增加试卷总分
        int res2 = baseMapper.update(null, new LambdaUpdateWrapper<Paper>()
                .setSql(" `paper_now_score`=`paper_now_score`+" + increaseScore)
                .eq(Paper::getPaperId, bos.get(0).getPaperId()));
        return res1 && res2 > 0;
    }

    /**
     * 试卷批量解绑题目
     *
     * @param bos
     * @return
     */
    @Transactional
    @Override
    public boolean removeQuByQuBo(List<PaperQuBo> bos) {
        if (bos.size() <= 0) {
            throw new ServiceException("待添加列表小于1");
        }
        Integer decreaseScore = bos.stream().map(bo -> bo.getQuScore())
                .reduce(0, (totalScore, score) -> totalScore + score);
        List<Long> ids = bos.stream().map(bo -> bo.getId()).collect(Collectors.toList());
        // 解绑题目
        int res1 = questionMapper.deleteBatchIds(ids);
        // 减少试卷总分
        int res2 = baseMapper.update(null, new LambdaUpdateWrapper<Paper>()
                .setSql(" `paper_now_score`=`paper_now_score`-" + decreaseScore)
                .eq(Paper::getPaperId, bos.get(0).getPaperId()));
        return res1 > 0 && res2 > 0;
    }

    /**
     * 试卷已绑定用户列表
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<PaperUserVo> bindUserList(PaperUserBo bo, PageQuery pageQuery) {
        if (ObjectUtil.isNull(baseMapper.selectById(bo.getPaperId()))) {
            throw new ServiceException("试卷不存在");
        }
        Page<PaperUserVo> qbUserVoPage = paperUserMapper.selectBindUserList(buildQueryWrapperUser(bo), pageQuery.build(), bo.getPaperId());
        return TableDataInfo.build(qbUserVoPage);
    }

    /**
     * 试卷未绑定用户列表
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<PaperUserVo> unBindUserList(PaperUserBo bo, PageQuery pageQuery) {
        if (ObjectUtil.isNull(baseMapper.selectById(bo.getPaperId()))) {
            throw new ServiceException("试卷不存在");
        }
        Page<PaperUserVo> qbUserVoPage = paperUserMapper.selectUnBindUserList(buildQueryWrapperUser(bo), pageQuery.build(), bo.getPaperId());
        return TableDataInfo.build(qbUserVoPage);
    }

    /**
     * 试卷批量绑定用户
     *
     * @param bos
     * @return
     */
    @Transactional
    @Override
    public boolean insertBatchUserByBo(List<PaperUserBo> bos) {
        List<PaperUser> paperUsers = BeanUtil.copyToList(bos, PaperUser.class);
        return paperUserMapper.insertBatch(paperUsers);
    }

    /**
     * 试卷批量解绑用户
     *
     * @param bos
     * @return
     */
    @Transactional
    @Override
    public boolean deleteBatchUserByBo(List<PaperUserBo> bos) {
        bos.forEach(bo -> {
            paperUserMapper.delete(new LambdaQueryWrapper<PaperUser>()
                    .eq(PaperUser::getUserId, bo.getUserId())
                    .eq(PaperUser::getPaperId, bo.getPaperId()));
        });
        return true;
    }

    // 部门用户查询条件
    private Wrapper<SysUser> buildQueryWrapperUser(PaperUserBo bo) {
        QueryWrapper<SysUser> wrapper = Wrappers.query();
        wrapper
                .eq("u.show_status", UserConstants.USER_NORMAL)
                .eq("u.status", UserConstants.USER_NORMAL)
                .like(StringUtils.isNotBlank(bo.getName()), "u.name", bo.getName())
                .and(ObjectUtil.isNotNull(bo.getDeptId()), w -> {
                    List<SysDept> deptList = deptMapper.selectList(new LambdaQueryWrapper<SysDept>()
                            .select(SysDept::getDeptId)
                            .apply(DataBaseHelper.findInSet(bo.getDeptId(), "ancestors")));
                    List<Long> ids = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());
                    ids.add(bo.getDeptId());
                    w.in("u.dept_id", ids);
                });
        return wrapper;
    }

    // 非空判断+界限判断+是否为客观题
    private boolean isObj(Integer quType) {
        if (quType.intValue() < 1 || quType.intValue() > 5) {
            throw new ServiceException("题目类型不符合规范");
        } else if (quType.intValue() >= 1 && quType.intValue() <= 3) {
            return true;
        } else {
            return false;
        }
    }
}
